package com.ly.common.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lzw on 2016/12/25.
 */
public class BeanUtil {
    /**
     * 将bean中的属性和值放入
     * @param obj
     * @return
     */
    public static Map<String,Object> getBeanAttr(Object obj){
        Map<String,Object> map= new HashMap<String,Object>();
        if(obj == null){
            return null;
        }
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    if(key!=null && value!=null){
                        map.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            map=null;
        }
        return map;
    }
}
